/*
 * Copyright (C), 2002-2016, 苏宁易购电子商务有限公司
 * FileName: BatchTransferData.java
 * Author:   16031333
 * Date:     2016年5月25日 上午10:30:43
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.hl.toolkit.server.suning.dto;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.suning.SuNingConfig;
import com.suning.epps.codec.Digest;
import com.suning.epps.codec.RSAUtil;
import com.suning.util.HttpClientUtil;
import com.suning.util.Util;
import com.util.DateUtils;

import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 批量转账 数据拼写
 * 
 * @author 16031333
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class BatchTransferData {

    private String publicKeyIndex = "0001";
    private String signAlgorithm = "RSA";
     private String inputCharset = "UTF-8";

    /**
     * 请求转账网关
     * 
     * @param baseUrl 请求业务数据 batchNum 请求的批次数目 detailNum 单批次中的明细数目
     * @return signature 签名
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     * @throws KeyManagementException
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本] （可选）
     */
    public String batchWithDraw(String baseUrl) throws InvalidKeyException, NoSuchAlgorithmException,
            InvalidKeySpecException, SignatureException, UnsupportedEncodingException,
            InvalidKeyException, KeyManagementException {

        String bussinessParam = bulidBatchContentJosn(2).toJSONString();

        String singnature = calculateSign(bussinessParam);
        String responseStr = HttpClientUtil.post(publicKeyIndex, signAlgorithm, SuNingConfig.merchantNo, inputCharset, baseUrl,
                singnature, bussinessParam);
        return responseStr;
    }

    /**
     * 计算签名
     *
     * @param body 请求业务数据
     * @return signature 签名
     * @throws InvalidKeyException
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本] （可选）
     */
    public String calculateSign(String body) throws NoSuchAlgorithmException, InvalidKeySpecException,
            InvalidKeyException, SignatureException, InvalidKeyException {
        Map<String, String> signMap = new HashMap<String, String>();
        signMap.put("merchantNo", SuNingConfig.merchantNo);
        signMap.put("publicKeyIndex",publicKeyIndex);
        signMap.put("inputCharset", "UTF-8");
        signMap.put("body", body);
        //      String wagKeyString = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALEhTthjWVcdzYkbrzW1eydORboUQPkWpuf_Phy9b3tt4Vz8wweI0cwGjB8owJIV_vLnNB-zikCWUOaaeey3MlrxqxKVqtI1GWWVJnTD7fcH_3JUo8Qs97AWoS869JRloDZADxFqHdcixr6n8W-N0fqjb43Fzp0LCZ6gABVb_38DAgMBAAECgYB3zVVsmdWFTI0FnQnmQ7bmINScRLKlRqLg6wvxmFbcnrb8k6C9adasLgl70a5doC7tz167yk1J3eEd94Fbj5SoNlZSYJvnA6eIKJ3LJtShAZLDed4PW4zNkcRqDMRSJrOgrjYVVs_XqOmvTFELyiCjxQtzhn0RR8rM0-10u7HfsQJBAPpFnF66jGVVpRpU2tmRtJwW6E6ScB_IxEhkwgcgZjLIyR18xxPE4kXLUh9ihfZSlsuMFfUp1njEYUDqSZ__BF0CQQC1LyVXmkGWKGIkxvnRaXaDrmLupTesaO8p4Uq9Wa3aGR6CggGhqc8rLFQpSRB0EaKT0wQ0HZYuH-1X6RQ1elrfAkEAuECxe8hJfn1MPROFv7IWzufKhbYn2C6d21JaypZexzqtXgk0I2jK0Wl7_2EwkQWCwT5UGBeCL40csIcMRz-ffQJARfPw7_Svs-Ddm6NzGoYkaszuh4Mkjp1pEXtZVugD9nvSSsMVDCy6vsl7qQD7qESSx44mRlTSAfbztQhZdBhMcwJABElZOJE1O4WHvjhzniLh5X1RelimfWOIubqDMtoP9o5iVhOwBK0B9kG4KxSagUvNNTQ2iIKeyzda0us4Ydf2mQ";
        String digest = Digest.digest(Digest.mapToString(Digest.treeMap(signMap)));
   //   PrivateKey privateKey = RSAUtil.getPrivateKey(wagKeyString);
		PrivateKey privateKey = RSAUtil.resolvePrivateKey("src/main/resources/RSA/private.key");
        
        String signature = RSAUtil.sign(digest, privateKey);

        return signature;
    }

    /**
     * 生成body批次数据
     * 
     * @param
     * @return JSONObject
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本] （可选）
     */
    public JSONObject bulidBatchContentJosn(int detailNum) {
        JSONObject contentObject = new JSONObject();
        String batchNo = Util.generalBatchNo();
        System.out.println(batchNo);
        contentObject.put("batchNo", batchNo);
        contentObject.put("merchantNo", SuNingConfig.merchantNo);// 70057241;70056575
        contentObject.put("productCode", "01070000042");
        contentObject.put("totalNum", detailNum);
        contentObject.put("totalAmount", 100 * detailNum);// 40*detailNum
        contentObject.put("currency", "CNY");
        contentObject.put("chargeMode", "01");
        String nowStr="";
        try {
			  nowStr=DateUtils.convertStringNowDate();
		} catch (ParseException e) {
		}
      contentObject.put("payDate", nowStr);
      
      contentObject.put("tunnelData", "{\"businessOrderId\":\"aaaaaaaaaaxxxxxxaaaaabe\"}");

        contentObject.put("goodsType", "220026");
        contentObject.put("remark", "这是一个demo");
        contentObject.put("notifyUrl", "http://10.24.42.78:8080/epps-demo/batchtransfer/notify.htm");
        contentObject.put("batchOrderName", "批量转账");
        contentObject.put("detailData", bulidDetailContentJosn(detailNum));
        return contentObject;
    }

    /**
     * 生成body明细数据
     * 
     * @param
     * @return JSONObject
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本] （可选）
     */
    public JSONArray bulidDetailContentJosn(int detailNum) {
        JSONArray detailArray = new JSONArray();
        for (int i = 0; i < detailNum; i++) {
            JSONObject detailObject = new JSONObject();
            detailObject.put("serialNo", Util.generalBatchNo());
            detailObject.put("receiverLoginName", "10852935016");
            // detailObject.put("receiverNo", "70056576");
            detailObject.put("receiverType", "PERSON");
            detailObject.put("receiverName", "妞妞");
            detailObject.put("amount", 100);
            detailObject.put("orderName", "运费险");
            detailObject.put("remark", "这是一个demo");
            detailArray.add(detailObject);
        }
        return detailArray;
    }

}
